<template>
	<view class="login-container">
		<view class="login-header">
			<text class="title">理财应用</text>
		</view>

		<view class="login-form">
			<view class="form-group">
				<u-input v-model="form.username" placeholder="请输入用户名" prefix-icon="account" />
			</view>

			<view class="form-group">
				<u-input v-model="form.password" placeholder="请输入密码" prefix-icon="lock" type="password" />
			</view>

			<view class="form-group">
				<view class="captcha-container">
					<u-input v-model="form.captcha" style="min-width: 140px;" placeholder="请输入验证码"
						prefix-icon="checkmark-circle" />
					<canvas class="captcha-canvas" width="120" height="45" canvas-id="captchaCanvas"
						@tap="refreshCaptcha"></canvas>
				</view>
			</view>

			<view class="form-group">
				<u-button type="primary" @click="handleLogin">立即登录</u-button>
			</view>

			<view class="register-link">
				<u-button type="text" @click="goToRegister">还没有账号？去注册</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import config from '../../config'
	import md5 from 'js-md5'
	export default {
		data() {
			return {
				form: {
					username: '',
					password: '',
					captcha: ''
				},
				captchaCode: ''
			}
		},
		methods: {
			// 生成验证码
			generateCaptcha() {
				const ctx = uni.createCanvasContext('captchaCanvas', this)
				const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ123456789'
				let code = ''

				// 清空画布
				ctx.clearRect(0, 0, 120, 40)

				// 绘制背景
				ctx.setFillStyle('#f5f5f5')
				ctx.fillRect(0, 0, 120, 40)

				// 绘制干扰线
				for (let i = 0; i < 3; i++) {
					ctx.setStrokeStyle(this.randomColor(150, 200))
					ctx.beginPath()
					ctx.moveTo(Math.random() * 120, Math.random() * 40)
					ctx.lineTo(Math.random() * 120, Math.random() * 40)
					ctx.stroke()
				}

				// 绘制验证码
				for (let i = 0; i < 4; i++) {
					const char = chars[Math.floor(Math.random() * chars.length)]
					code += char
					ctx.setFontSize(20)
					ctx.setFillStyle(this.randomColor(50, 150))
					ctx.rotate(Math.random() * 0.4 - 0.2)
					ctx.fillText(char, 20 + i * 20, 25)
					ctx.rotate(-(Math.random() * 0.4 - 0.2))
				}

				this.captchaCode = code.toLowerCase()
				ctx.draw()
			},

			// 生成随机颜色
			randomColor(min, max) {
				const r = Math.floor(Math.random() * (max - min) + min)
				const g = Math.floor(Math.random() * (max - min) + min)
				const b = Math.floor(Math.random() * (max - min) + min)
				return `rgb(${r},${g},${b})`
			},

			// 刷新验证码
			refreshCaptcha() {
				this.generateCaptcha()
			},

			// 处理登录
			handleLogin() {
				if (!this.form.username) {
					uni.showToast({
						title: '请输入用户名',
						icon: 'none'
					})
					return
				}

				if (!this.form.password) {
					uni.showToast({
						title: '请输入密码',
						icon: 'none'
					})
					return
				}

				if (!this.form.captcha) {
					uni.showToast({
						title: '请输入验证码',
						icon: 'none'
					})
					return
				}

				if (this.form.captcha.toLowerCase() !== this.captchaCode) {
					uni.showToast({
						title: '验证码错误',
						icon: 'none'
					})
					return
				}

				// 对密码进行MD5加密
				const encryptedPassword = md5(this.form.password)

				// 模拟登录成功
				// TODO: 替换为实际的登录接口调用
				uni.request({
					url: "/api/login/verifyLogin",
					method: 'GET',
					data: {
						username: this.form.username,
						password: encryptedPassword
					},
					success: (res) => {
						if (res !== null) {
							// 保存token到本地存储
							uni.setStorageSync('user', res)
							uni.request({
								url: "/api/bf/user/message/nopage",
								data: {
									user: res
								},
								method: 'POST',
								success(res1) {
									let infoPageInfo = res1.data.infoPageInfo.filter(i => i.status ===
										0)
									let content = "您有" + infoPageInfo.length + "条投资信息未查看，请点击查看~"
									let options = {
										"cover": false,
										"when": new Date(),
										"title": "通知消息"
									}
									let body = {
										"id": "id",
										"key": "key"
									}
									let payload = JSON.stringify(body)
									plus.push.createMessage(content, payload, options)
								}
							})
							// 跳转到首页
							uni.reLaunch({
								url: '/pages/pf/pf'
							})
						} else {
							uni.showToast({
								title: res.data.message || '登录失败',
								icon: 'none'
							})
						}
					},
					fail: (res) => {
						console.log(res);
						uni.showToast({
							title: '网络错误',
							icon: 'none'
						})
					}
				})
			},

			// 跳转到注册页面
			goToRegister() {
				uni.navigateTo({
					url: '/pages/register/register'
				})
			}
		},
		onReady() {
			let token = uni.getStorageSync("user")
			if (token !== "") uni.reLaunch({
				url: '/pages/pf/pf'
			})
			this.generateCaptcha()
		}
	}
</script>

<style lang="scss">
	.login-container {
		padding: 40rpx;

		.login-header {
			text-align: center;
			margin-bottom: 60rpx;

			.title {
				font-size: 48rpx;
				font-weight: bold;
				color: #333;
			}
		}

		.login-form {
			.form-group {
				margin-bottom: 30rpx;
			}

			.captcha-container {
				display: flex;
				align-items: center;

				.captcha-canvas {
					width: 120px;
					height: 45px;
					margin-left: 48rpx;
				}
			}

			.register-link {
				text-align: center;
				margin-top: 40rpx;

				.u-button {
					font-size: 28rpx;
					color: #2979ff;
					padding: 0;
					background: none;
					position: relative;
					display: inline-block;

					&::after {
						border: none;
					}

					&::before {
						content: '';
						position: absolute;
						bottom: -4rpx;
						left: 0;
						width: 100%;
						height: 2rpx;
						background: #2979ff;
						transform: scaleX(0);
						transform-origin: right;
						transition: transform 0.3s ease;
					}

					&:hover::before,
					&:active::before {
						transform: scaleX(1);
						transform-origin: left;
					}

					&:active {
						opacity: 0.8;
					}
				}
			}
		}
	}
</style>